/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package client.network;
import java.io.*;
import java.net.*;
import client.logic.ClientLogicImplement.*;
import com.cse.p2p.common.*;
/**
 *
 * @author TuyetNgan
 */
public class SendTask implements Runnable  {

        private File file;
        private int portNumber = 2000;
        private Socket socket = null;
        private OutputStream os = null;
        private String IPsender;

        public SendTask(File f, String ip) {
            this.file = f;
            this.IPsender = ip;
        }
        public void  newConnection(){
            try{
                socket = new Socket(IPsender, portNumber);
                os = socket.getOutputStream();
            }
            catch(IOException e){}
        }
        public void closeConnection(){
			try {
                os.close();
                socket.close();
			}
			catch (IOException e){}
        }

        @Override
        public void run() {
            newConnection();
            System.out.println("Client sending... ");
            try {
                byte[] mybytearray = new byte[client.logic.ClientLogicImplement.choosePiecesSize()];
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                int bytesRead;
                while((bytesRead = bis.read(mybytearray, 0, mybytearray.length)) != -1){
                  os.write(mybytearray, 0, bytesRead);
                  os.flush();
                }
                bis.close();
            } catch (EOFException ex) {}
            catch (UnknownHostException i){}
            catch (IOException i){}

            closeConnection();
        }
    }
